package com.sssre.lttcloud.config.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sssre.lttcloud.api.entity.Config;
import com.sssre.lttcloud.common.result.Result;
import com.sssre.lttcloud.common.result.ResultCode;
import com.sssre.lttcloud.common.utils.RedisUtil;
import com.sssre.lttcloud.config.mapper.ConfigMapper;
import com.sssre.lttcloud.config.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 系统配置服务实现类
 * 
 * @author 浪兎兎
 * @since 2025/6/22 16:54
 */
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements ConfigService {

    @Autowired
    private ConfigMapper configMapper;

    @Autowired
    private RedisUtil redisUtil;

    private static final String CONFIG_CACHE_PREFIX = "config:";
    private static final String CONFIG_KEY_CACHE_PREFIX = "config_key:";
    private static final long CONFIG_CACHE_EXPIRE = 3600; // 1小时

    @Override
    public Result getConfigPage(Integer pageNum, Integer pageSize, String configName, String configKey) {
        try {
            // 创建分页对象
            Page<Config> page = new Page<>(pageNum, pageSize);
            
            // 构建查询条件
            LambdaQueryWrapper<Config> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(StringUtils.hasText(configName), Config::getConfigName, configName)
                       .like(StringUtils.hasText(configKey), Config::getConfigKey, configKey)
                       .orderByDesc(Config::getCreateTime);
            
            // 执行分页查询
            IPage<Config> result = this.page(page, queryWrapper);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "分页查询配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Config>> getAllConfigs() {
        try {
            // 先从缓存获取
            String cacheKey = CONFIG_CACHE_PREFIX + "all";
            List<Config> cachedConfigs = (List<Config>) redisUtil.get(cacheKey);
            if (cachedConfigs != null) {
                return Result.success(cachedConfigs);
            }
            
            // 缓存未命中，从数据库查询
            LambdaQueryWrapper<Config> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Config::getStatus, 1)
                       .orderByAsc(Config::getConfigType)
                       .orderByAsc(Config::getConfigKey);
            
            List<Config> configs = this.list(queryWrapper);
            
            // 存入缓存
            redisUtil.set(cacheKey, configs, CONFIG_CACHE_EXPIRE, TimeUnit.SECONDS);
            
            return Result.success(configs);
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "查询所有配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Config> getConfigById(Long id) {
        try {
            if (id == null) {
                return Result.failed(ResultCode.VALIDATE_FAILED, "配置ID不能为空");
            }
            
            Config config = this.getById(id);
            if (config == null) {
                return Result.failed(ResultCode.DATA_NOT_FOUND, "配置不存在");
            }
            
            return Result.success(config);
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "查询配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> getConfigValue(String configKey) {
        try {
            if (!StringUtils.hasText(configKey)) {
                return Result.failed(ResultCode.VALIDATE_FAILED, "配置键不能为空");
            }
            
            // 先从缓存获取
            String cacheKey = CONFIG_KEY_CACHE_PREFIX + configKey;
            String cachedValue = redisUtil.get(cacheKey).toString();
            if (cachedValue != null) {
                return Result.success(cachedValue);
            }
            
            // 缓存未命中，从数据库查询
            LambdaQueryWrapper<Config> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Config::getConfigKey, configKey)
                       .eq(Config::getStatus, 1);
            
            Config config = this.getOne(queryWrapper);
            if (config == null) {
                return Result.failed(ResultCode.DATA_NOT_FOUND, "配置不存在或已禁用");
            }
            
            // 存入缓存
            redisUtil.set(cacheKey, config.getConfigValue(), CONFIG_CACHE_EXPIRE, TimeUnit.SECONDS);
            
            return Result.success(config.getConfigValue());
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "查询配置值失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> addConfig(Config config) {
        try {
            if (config == null) {
                return Result.failed(ResultCode.VALIDATE_FAILED, "配置信息不能为空");
            }
            
            // 检查配置键是否唯一
            Result<Boolean> uniqueResult = checkConfigKeyUnique(config.getConfigKey(), null);
            if (!uniqueResult.isSuccess() || !uniqueResult.getData()) {
                return Result.failed(ResultCode.DATA_ALREADY_EXISTS, "配置键已存在");
            }
            
            // 设置默认值
            if (config.getConfigType() == null) {
                config.setConfigType(1); // 默认为系统配置
            }
            if (config.getStatus() == null) {
                config.setStatus(1); // 默认启用
            }
            
            // 保存配置
            boolean success = this.save(config);
            if (!success) {
                return Result.failed(ResultCode.OPERATION_FAILED, "保存配置失败");
            }
            
            // 清除相关缓存
            clearConfigCache();
            
            return Result.success("配置添加成功");
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "添加配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> updateConfig(Config config) {
        try {
            if (config == null || config.getId() == null) {
                return Result.failed(ResultCode.VALIDATE_FAILED, "配置信息或ID不能为空");
            }
            
            // 检查配置是否存在
            Config existingConfig = this.getById(config.getId());
            if (existingConfig == null) {
                return Result.failed(ResultCode.DATA_NOT_FOUND, "配置不存在");
            }
            
            // 检查配置键是否唯一（排除当前记录）
            Result<Boolean> uniqueResult = checkConfigKeyUnique(config.getConfigKey(), config.getId());
            if (!uniqueResult.isSuccess() || !uniqueResult.getData()) {
                return Result.failed(ResultCode.DATA_ALREADY_EXISTS, "配置键已存在");
            }
            
            // 更新配置
            boolean success = this.updateById(config);
            if (!success) {
                return Result.failed(ResultCode.OPERATION_FAILED, "更新配置失败");
            }
            
            // 清除相关缓存
            clearConfigCache();
            
            return Result.success("配置更新成功");
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "更新配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> deleteConfig(Long id) {
        try {
            if (id == null) {
                return Result.failed(ResultCode.VALIDATE_FAILED, "配置ID不能为空");
            }
            
            // 检查配置是否存在
            Config config = this.getById(id);
            if (config == null) {
                return Result.failed(ResultCode.DATA_NOT_FOUND, "配置不存在");
            }
            
            // 删除配置（逻辑删除）
            boolean success = this.removeById(id);
            if (!success) {
                return Result.failed(ResultCode.OPERATION_FAILED, "删除配置失败");
            }
            
            // 清除相关缓存
            clearConfigCache();
            
            return Result.success("配置删除成功");
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "删除配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> deleteConfigs(List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.failed(ResultCode.VALIDATE_FAILED, "配置ID列表不能为空");
            }
            
            // 批量删除配置（逻辑删除）
            boolean success = this.removeByIds(ids);
            if (!success) {
                return Result.failed(ResultCode.OPERATION_FAILED, "批量删除配置失败");
            }
            
            // 清除相关缓存
            clearConfigCache();
            
            return Result.success("批量删除配置成功");
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "批量删除配置失败: " + e.getMessage());
        }
    }

    @Override
    public Result<Boolean> checkConfigKeyUnique(String configKey, Long id) {
        try {
            if (!StringUtils.hasText(configKey)) {
                return Result.failed(ResultCode.VALIDATE_FAILED, "配置键不能为空");
            }
            
            LambdaQueryWrapper<Config> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Config::getConfigKey, configKey);
            
            // 如果是更新操作，排除当前记录
            if (id != null) {
                queryWrapper.ne(Config::getId, id);
            }
            
            long count = this.count(queryWrapper);
            boolean isUnique = count == 0;
            
            return Result.success(isUnique);
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "检查配置键唯一性失败: " + e.getMessage());
        }
    }

    @Override
    public Result<String> refreshConfigCache() {
        try {
            // 清除所有配置相关缓存
            clearConfigCache();
            
            // 重新加载配置到缓存
            Result<List<Config>> configsResult = getAllConfigs();
            if (!configsResult.isSuccess()) {
                return Result.failed(ResultCode.OPERATION_FAILED, "刷新配置缓存失败");
            }
            
            return Result.success("配置缓存刷新成功");
        } catch (Exception e) {
            return Result.failed(ResultCode.SYSTEM_ERROR, "刷新配置缓存失败: " + e.getMessage());
        }
    }

    /**
     * 清除配置相关缓存
     */
    private void clearConfigCache() {
        try {
            // 清除所有配置缓存
            redisUtil.deleteByPattern(CONFIG_CACHE_PREFIX + "*");
            redisUtil.deleteByPattern(CONFIG_KEY_CACHE_PREFIX + "*");
        } catch (Exception e) {
            // 记录日志但不影响业务
            System.err.println("清除配置缓存失败: " + e.getMessage());
        }
    }

    // ==================== IService 接口实现 ====================

    @Override
    public boolean saveBatch(Collection<Config> entityList, int batchSize) {
        try {
            return super.saveBatch(entityList, batchSize);
        } catch (Exception e) {
            System.err.println("批量保存配置失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<Config> entityList, int batchSize) {
        try {
            boolean result = super.saveOrUpdateBatch(entityList, batchSize);
            if (result) {
                clearConfigCache();
            }
            return result;
        } catch (Exception e) {
            System.err.println("批量保存或更新配置失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean updateBatchById(Collection<Config> entityList, int batchSize) {
        try {
            boolean result = super.updateBatchById(entityList, batchSize);
            if (result) {
                clearConfigCache();
            }
            return result;
        } catch (Exception e) {
            System.err.println("批量更新配置失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public boolean saveOrUpdate(Config entity) {
        try {
            boolean result = super.saveOrUpdate(entity);
            if (result) {
                clearConfigCache();
            }
            return result;
        } catch (Exception e) {
            System.err.println("保存或更新配置失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public Config getOne(Wrapper<Config> queryWrapper, boolean throwEx) {
        try {
            return super.getOne(queryWrapper, throwEx);
        } catch (Exception e) {
            System.err.println("查询配置失败: " + e.getMessage());
            return null;
        }
    }

    @Override
    public Map<String, Object> getMap(Wrapper<Config> queryWrapper) {
        try {
            return super.getMap(queryWrapper);
        } catch (Exception e) {
            System.err.println("查询配置Map失败: " + e.getMessage());
            return null;
        }
    }

    @Override
    public <V> V getObj(Wrapper<Config> queryWrapper, Function<? super Object, V> mapper) {
        try {
            return super.getObj(queryWrapper, mapper);
        } catch (Exception e) {
            System.err.println("查询配置对象失败: " + e.getMessage());
            return null;
        }
    }

    @Override
    public ConfigMapper getBaseMapper() {
        return configMapper;
    }
}
